package com.iye.puretennis.fragment;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.app.FragmentActivity;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import com.iye.puretennis.R;
import com.iye.puretennis.activity.MainTabsActivity;
import com.iye.puretennis.custom.CustomTimePicker;
import com.iye.puretennis.custom.DateTimePickerWindow;
import com.iye.puretennis.custom.HuaWenHuPoEditText;
import com.iye.puretennis.custom.HuaWenHuPoTextView;
import com.iye.puretennis.domain.PaymentWay;
import com.iye.puretennis.domain.UrlSuffix;
import com.iye.puretennis.domain.User;
import com.iye.puretennis.helper.Constant;
import com.iye.puretennis.helper.RemoteUrlCollections;
import com.iye.puretennis.helper.ServerAccessHelper;
import com.iye.puretennis.helper.Session;
import com.iye.puretennis.utils.StringUtils;
import com.iye.puretennis.utils.TimeUtils;
import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jing wu
 * Date: 2014/12/5
 * Time: 15:45
 */
public class CreateAppointmentFragment extends TabFragment {


    public static final String TAG = "create_appointment";

    public static final int MINUTE_INTERVAL = 15;

    private HuaWenHuPoEditText periodsText;

    private HuaWenHuPoEditText locationText;

    private SeekBar personAmount;

    private List<User> users;

    private PaymentWay paymentWay = PaymentWay.AA;

    private int year;

    private int month;

    private int day;

    private int hourFrom;

    private int minuteFrom;

    private int hourTo;

    private int minuteTo;

    private AlertDialog show;

    private View invitationArea;

    @Override
    public void onCustomCreateView(LayoutInflater inflater) {

        Session session = Session.newSession();

        users = (List<User>) session.get("selectedUsers");

        final ImageButton saveButton = (ImageButton) mainView.findViewById(R.id.save_button);

        final ImageView closeIcon = (ImageView) mainView.findViewById(R.id.icon_close);

        invitationArea = mainView.findViewById(R.id.invitation_area);
        if (users.isEmpty()) {
            invitationArea.setVisibility(View.GONE);
        }else{
            invitationArea.setVisibility(View.VISIBLE);

            HuaWenHuPoTextView invitationsText = (HuaWenHuPoTextView) mainView.findViewById(R.id.invitations);

            invitationsText.setText(getInvitationsText(users));


        }


        periodsText = (HuaWenHuPoEditText) mainView.findViewById(R.id.times);

        locationText = (HuaWenHuPoEditText) mainView.findViewById(R.id.location);


        periodsText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hideIM(view);
                showDateTimePicker();
            }
        });

        periodsText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean focus) {
                if (focus) {
                    hideIM(view);
                    showDateTimePicker();
                }
            }
        });

        final HuaWenHuPoTextView paymentAA = (HuaWenHuPoTextView) mainView.findViewById(R.id.payment_aa);
        final HuaWenHuPoTextView paymentMine = (HuaWenHuPoTextView) mainView.findViewById(R.id.payment_mine);
        final HuaWenHuPoTextView paymentNotSure = (HuaWenHuPoTextView) mainView.findViewById(R.id.payment_not_sure);

        View.OnClickListener buttonOnClickListener = new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int viewId = view.getId();
                Resources resources = getResources();
                if (viewId == closeIcon.getId()) {
                    invitationArea.setVisibility(View.GONE);
                } else if (viewId == saveButton.getId()) {
                    createAppointment();
                } else if (viewId == paymentAA.getId()) {
                    paymentAA.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_left));
                    paymentMine.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_center_u));
                    paymentNotSure.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_right_u));
                    paymentWay = PaymentWay.AA;
                } else if (viewId == paymentMine.getId()) {
                    paymentAA.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_left_u));
                    paymentMine.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_center));
                    paymentNotSure.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_right_u));
                    paymentWay = PaymentWay.MINE;
                } else if (viewId == paymentNotSure.getId()) {
                    paymentAA.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_left_u));
                    paymentMine.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_center_u));
                    paymentNotSure.setBackgroundDrawable(resources.getDrawable(R.drawable.appointment_right));
                    paymentWay = PaymentWay.NOT_SURE;
                }
            }
        };

        closeIcon.setOnClickListener(buttonOnClickListener);
        saveButton.setOnClickListener(buttonOnClickListener);
        paymentAA.setOnClickListener(buttonOnClickListener);
        paymentMine.setOnClickListener(buttonOnClickListener);
        paymentNotSure.setOnClickListener(buttonOnClickListener);
    }


    private void showDateTimePicker() {

        if (show == null) {
            final FragmentActivity activity = getActivity();
            final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
            View dateTimePickerView = View.inflate(activity, R.layout.datetime_picker, null);
            DatePicker datePicker = (DatePicker) dateTimePickerView.findViewById(R.id.date_picker);
            datePicker.setCalendarViewShown(false);

            CustomTimePicker timePickerFrom = (CustomTimePicker) dateTimePickerView.findViewById(R.id.time_picker_from);
            timePickerFrom.setIs24HourView(true);
            CustomTimePicker timePickerTo = (CustomTimePicker) dateTimePickerView.findViewById(R.id.time_picker_to);
            timePickerTo.setIs24HourView(true);

            Calendar calendar = Calendar.getInstance();

            year = calendar.get(Calendar.YEAR);
            month = calendar.get(Calendar.MONTH);
            day = calendar.get(Calendar.DAY_OF_MONTH);
            int realHour = calendar.get(Calendar.HOUR_OF_DAY);
            int realMinute = calendar.get(Calendar.MINUTE);
            minuteFrom = minuteTo = TimeUtils.getAppointmentTimeMinute(realMinute);
            hourFrom = TimeUtils.getAppointmentTimeHour(realHour, realMinute);
            hourTo = hourFrom + 2;
            datePicker.setMinDate(calendar.getTimeInMillis() - 1000);
            datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
                @Override
                public void onDateChanged(DatePicker datePicker, int year, int month, int day) {

                    CreateAppointmentFragment.this.year = year;
                    CreateAppointmentFragment.this.month = month;
                    CreateAppointmentFragment.this.day = day;

                }
            });


            timePickerFrom.setCurrentHour(hourFrom);
            timePickerFrom.setCurrentMinute(minuteFrom);
            timePickerTo.setCurrentHour(hourTo);
            timePickerTo.setCurrentMinute(minuteTo);
            timePickerFrom.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

                @Override
                public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                    if (hour > hourTo || (hour == hourTo && minute > minuteTo)) {
                        timePicker.setCurrentHour(hourFrom);
                        timePicker.setCurrentMinute(minuteFrom);
                    } else {
                        CreateAppointmentFragment.this.hourFrom = hour;
                        CreateAppointmentFragment.this.minuteFrom = minute;

                    }
                }
            });

            timePickerTo.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {

                @Override
                public void onTimeChanged(TimePicker timePicker, int hour, int minute) {
                    if (hourFrom > hour || (hourFrom == hour && minuteFrom > minute)) {
                        timePicker.setCurrentHour(hourTo);
                        timePicker.setCurrentMinute(minuteTo);
                    } else {
                        CreateAppointmentFragment.this.hourTo = hour;
                        CreateAppointmentFragment.this.minuteTo = minute;

                    }

                }
            });

            final HuaWenHuPoTextView okView = (HuaWenHuPoTextView) dateTimePickerView.findViewById(R.id.ok_btn);
            HuaWenHuPoTextView cancelView = (HuaWenHuPoTextView) dateTimePickerView.findViewById(R.id.cancel_btn);
            builder.setView(dateTimePickerView);
            show = builder.show();
            show.setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialogInterface) {

                    show = null;
                }
            });
            View.OnClickListener buttonClickListener = new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    int id = view.getId();
                    if (okView.getId() == id) {
                        showDateTime();
                    }
                    show.dismiss();
                }
            };
            okView.setOnClickListener(buttonClickListener);
            cancelView.setOnClickListener(buttonClickListener);
        }

    }


    private void getLastLocation() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                final String result = ServerAccessHelper.queryStringForGet(RemoteUrlCollections.getUrl(UrlSuffix.LAST_LOCATION), token.getToken());

                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!Constant.RESPONSE_BADLY.equals(result)) {
                            try {
                                JSONObject json = new JSONObject(result);

                                String location = json.getString("location");

                                locationText.setText(location);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });

            }
        }).start();
    }


    private void createAppointment() {
        HuaWenHuPoEditText noteText = (HuaWenHuPoEditText) mainView.findViewById(R.id.note);
        final String location = locationText.getText().toString();
        final String note = noteText.getText().toString();

        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject appointmentJsonObj = new JSONObject();
                JSONArray invitees = new JSONArray();
                JSONArray periods = new JSONArray();

                try {
                    for (User user : users) {
                        JSONObject userObject = new JSONObject();
                        userObject.put("guid", user.getGuid());
                        userObject.put("name", user.getName());
                        invitees.put(userObject);
                    }
                    appointmentJsonObj.put("date", getDate());

                    periods.put(getTimeFrom());
                    periods.put(getTimeTo());

                    appointmentJsonObj.put("periods", periods);

                    appointmentJsonObj.put("location", location);

                    appointmentJsonObj.put("participantsAmount", getParticipantsAmount(personAmount.getProgress()));

                    appointmentJsonObj.put("paymentWay", paymentWay.name());

                    appointmentJsonObj.put("note", note);

                    appointmentJsonObj.put("invitees", invitees);

                    StringEntity paramEntity = new StringEntity(appointmentJsonObj.toString(), Constant.CHARSET_UTF8);
                    ServerAccessHelper.queryStringForPost(RemoteUrlCollections.getUrl(UrlSuffix.APPOINTMENT), token.getToken(), paramEntity);
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            Toast.makeText(getActivity(), getString(R.string.create_appointment_sucess), Toast.LENGTH_SHORT).show();
                            onBackPressed();
                        }
                    });
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private String getInvitationsText(List<User> users) {
        String invitationsText = Constant.INVITATIONS_TEXT_PREFIX;
        String defaultTextSeparator = Constant.DEFAULT_TEXT_SEPARATOR;
        int size = users.size();
        for (int i = 0; i < size; i++) {
            User user = users.get(i);
            if (i == 0) {
                invitationsText = invitationsText + user.getName();
            } else {
                invitationsText = invitationsText + " " + defaultTextSeparator + user.getName();
            }
        }
        return invitationsText;
    }

    protected void showDateTime() {
        periodsText.setText(year + getString(R.string.year) + (month + 1) + getString(R.string.month) + day + getString(R.string.day) + " " + TimeUtils.formatTime(hourFrom) + ":" + TimeUtils.formatTime(minuteFrom * MINUTE_INTERVAL) + " - " + TimeUtils.formatTime(hourTo) + ":" + TimeUtils.formatTime(minuteTo * MINUTE_INTERVAL));
    }


    @Override
    public int getViewId() {
        return R.layout.create_appointment;
    }

    @Override
    public int getSourceId() {
        return R.id.create_appointment;
    }

    @Override
    public void updateUI() {
        personAmount = (SeekBar) mainView.findViewById(R.id.person_amount);

        personAmount.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
                if (progress <= 20) {
                    seekBar.setProgress(5);
                } else if (progress > 20 && progress <= 40) {
                    seekBar.setProgress(30);
                } else if (progress > 40 && progress <= 60) {
                    seekBar.setProgress(50);
                } else if (progress > 60 && progress <= 80) {
                    seekBar.setProgress(70);
                } else {
                    seekBar.setProgress(95);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
        getLastLocation();
    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private String getDate() {
        return year + "-" + TimeUtils.formatTime(month + 1) + "-" + TimeUtils.formatTime(day);
    }

    private String getTimeFrom() {
        return TimeUtils.formatTime(hourFrom) + ":" + TimeUtils.formatTime(minuteFrom * MINUTE_INTERVAL);
    }

    private String getTimeTo() {
        return TimeUtils.formatTime(hourTo) + ":" + TimeUtils.formatTime(minuteTo * MINUTE_INTERVAL);
    }

    private int getParticipantsAmount(int progress) {
        switch (progress) {
            case 5:
                return 2;
            case 30:
                return 3;
            case 50:
                return 4;
            case 70:
                return 5;
            default:
                return 6;
        }
    }


}
